<?

////////////// TEMP TEMP TEMP ////////////////


if( $_GET[ "up" ]) {

////////////// HTML5 style
//getstring = "?up=true&account=" + init.account + "&auth=" + init.uid + "&type=media.csv";

$_SESSION['uid'] = (int) $_GET['auth'];
$currentid = $DB->query_direct( "select max(ID) from db_media" );

$DB->set( $DB->simplestring( $_GET[ "type" ]), array( "ID"=> ($currentid +1), "flog"=> date( "Y-m-d" ), "llog"=> date( "Y-m-d" ), "creator"=> $_SESSION[ 'uid' ], "active"=> 1 ));

$upload_folder = ROOT . ACCOUNT ."/www/DB/media/";



if(count($_FILES)>0) { //browser supported sendAsBinary()
	if( move_uploaded_file( $_FILES['upload']['tmp_name'] , $upload_folder.'/'. ( ++$currentid ) . ".csv" ) ) { //$_FILES['upload']['name']
		echo json_encode( array( array( "id"=> $currentid, "type"=> $_GET[ 'type' ])));
	}
	exit();
} else {

	if(isset($_GET['base64'])) {
		$content = base64_decode(file_get_contents('php://input'));
	} else {
		$content = file_get_contents('php://input');
	}

	$headers = getallheaders();
	
	$headers = array_change_key_case($headers, CASE_UPPER); //different case was being used for different browsers
	
	if(file_put_contents($upload_folder.'/'. ( ++$currentid ) . ".csv", $content)) { //$headers['UP-FILENAME']
		echo json_encode( array( array( "id"=> $currentid, "type"=> $_GET[ 'type' ])));
	}
	exit();
}













} else {

////////////// SWFUPLOAD style

$_SESSION['uid'] = $DB->smartq( $_POST['auth'], "int" );

$maxsize = 26214400;
$folder = ROOT . ACCOUNT ."/www/DB/media/";

if( isset($_FILES['Filedata']) && is_array($_FILES['Filedata']) && isset(
	$_FILES['Filedata']['tmp_name'],
	$_FILES['Filedata']['name'],
	$_FILES['Filedata']['size'],
	$_FILES['Filedata']['error'])) {
		
		$active = isset( $_POST['active'] )? (int) $_POST['active'] : 1;
		
	$newid = $DB->query_direct( "select max(ID) from db_media" ) + 1;
	$DB->query( "INSERT INTO db_media (ID, `type`, flog, creator, active, meta) VALUES ($newid, ".(int)$_POST['objtype'].", NOW(), '".$_user['ID']."', $active, '{\"raw\":\"".$_FILES['Filedata']['name']."\"}')" );
	if($_POST['parentid']) $DB->query( "INSERT INTO glue_object (parenttype,parentid,objtype,objid,rank ) VALUES ('".(int)$_POST['parenttype']."', '".(int)$_POST['parentid']."', '".(int)$_POST['objtype']."', $newid, 5 )" );
	
	$ext = array_pop(explode(".",strtolower($_FILES['Filedata']['name'])));
	if( intval($_FILES['Filedata']['size']) <= $maxsize && intval($_FILES['Filedata']['error']) === 0 &&
		@move_uploaded_file( $_FILES['Filedata']['tmp_name'], $folder.$newid.".".(($ext=="jpeg")?"jpg":$ext)) ) {
			//$removefile = $folder.$_FILES['Filedata']['name'];
			echo $newid;
	} else @unlink($_FILES['Filedata']['tmp_name']);
}

}